<template>
  <div class="pay_page">
    <u-card
      class="takeout"
      :title="takeOutTitle"
      :title-color="`#fff`"
      :head-style="cardHeadClass[0]"
    >
      <!-- :body-style="orderType == 'takein' ? cardBodyClass[0]:''" -->

      <view class="" slot="body">
        <view
          class="u-body-item u-flex u-border-bottom"
          @tap="handlerChooseReceiVerAddress"
        >
          <view class="add_info left" v-if="hasReceiverAddress == true">
            <view class="address">{{
              addressReceiver.receiverDetailAddresss
            }}</view>
            <view class="member">
              <text class="mr-20">{{ addressReceiver.receiverName }}</text>
              <text>{{ addressReceiver.receiverPhone }}</text>
            </view>
          </view>
          <view class="left" v-else>
            <view class="tips" v-show="orderType == 'takeout'">
              选择一个地址
            </view>
            <view class="tips" v-show="orderType == 'takein'">
              选择一个收件人
            </view>
          </view>
          <view class="right">
            <u-icon name="arrow-right"></u-icon>
          </view>
          <!-- 选择地址的 列 选择器 -->
        </view>

        <view
          class="u-body-item u-flex u-border-bottom"
          v-show="orderType == 'takein'"
        >
          <view class="left">
            <view>
              <!-- <view class="time"> 预计送达时间 </view> -->
              <view class="tips"> 请于30分钟后取餐. </view>
            </view>
          </view>
          <view class="right">
            {{ thirtyMinutesAfter }}
            <!-- <u-icon name="arrow-right"></u-icon> -->
          </view>
        </view>

        <view
          v-show="orderType == 'takeout'"
          class="u-body-item u-flex u-row-between u-p-b-0"
        >
          <view class="left">
            <view>
              <view class="time"> 预计送达时间 </view>
              <view class="tips"> 特殊时期减少接触,请修改下方订单备注. </view>
            </view>
          </view>
          <view class="right">
            {{
              expectedReceiverTime ? expectedReceiverTime : thirtyMinutesAfter
            }}
            <u-icon
              name="arrow-right"
              @tap="selectListShow = !selectListShow"
            ></u-icon>
            <u-select
              v-model="selectListShow"
              :list="selectList"
              @confirm="selectListConfirm"
            ></u-select>
          </view>
        </view>
      </view>
    </u-card>

    <u-card title="支付方式">
      <view class="" slot="body">
        <view class="u-body-item u-flex">
          <view class="left">支付宝</view>
          <view class="right">
            <u-switch
              v-model="zfbChecked"
              :disabled="true"
              :size="30"
            ></u-switch>
          </view>
        </view>
      </view>
    </u-card>
    <u-card :head-style="cardHeadClass[1]">
      <view class="cart" slot="body">
        <view
          class="u-body-item u-flex u-border-bottom"
          v-for="(item, index) in cart"
          :key="index"
        >
          <!-- v-for   商品 -->
          <view class="left">
            <view class="img">
              <img :src="OrderItemImg(item.id)" alt="" />
            </view>
            <view class="content">
              <view class="name">
                {{ item.name }}
              </view>
              <view class="props">
                {{ item.props_text }}
              </view>
              <view class="number"> x {{ item.number }} </view>
            </view>
          </view>
          <view class="right">
            <view class="price"> ￥{{ item.price }} </view>
          </view>
        </view>
        <view
          class="u-body-item u-flex"
          v-for="orderOtherPrice in orderOtherPrices"
          :key="orderOtherPrice.title"
        >
          <view class="left">
            {{ orderOtherPrice.title }}
          </view>
          <view class="right">
            {{ orderOtherPrice.price }}
          </view>
        </view>
      </view>
    </u-card>

    <u-card :head-style="cardHeadClass[1]">
      <view class="" slot="body">
        <view class="u-body-item u-flex" @tap.stop="textParseShow = true">
          <view class="left"> 备注 </view>
          <view class="content">
            <!-- 这是备注这是备注  -->
          </view>
          <view class="right">
            <view class="place_holder" v-if="order.remark">
              {{ order.remark }}
            </view>
            <view class="place_holder" v-else> 口味、偏好等要求 </view>
            <u-icon name="arrow-right"></u-icon>
          </view>
        </view>
        <!-- 
        <view class="u-body-item u-flex">
          <view class="left"> 餐具数量 </view>
          <view class="right">
            <view class="place_holder">未选择</view>
            <u-icon name="arrow-right"></u-icon>
          </view>
        </view> -->

        <!-- <view class="u-body-item u-flex">
          <view class="left"> 发票 </view>
          <view class="right">
            <view class="place_holder">未选择</view>
            <u-icon name="arrow-right"></u-icon>
          </view>
        </view> -->
      </view>
    </u-card>

    <!-- 地址选择 -->
    <popup-layer
      direction="top"
      :show-pop="AddressPopupVisible"
      class="address_select"
      @openpopup="showAddressSelect"
    >
      <template slot="content">
        <!-- <view>123</view> -->
        <view class="add-list">
          <view class="wrapper">
            <!-- address list 渲染  address 放在 computed 中-->
            <!-- {{ addressList }} -->
            <scroll-view scroll-y @touchmove.stop.prevent>
              <u-card :head-style="cardHeadClass[1]">
                <view class="" slot="body" v-if="addressList.length">
                  <view
                    class="u-body-item u-flex u-border-bottom"
                    v-for="(add, index) in addressList"
                    :key="index"
                    @tap="handlerChooseAddress(add)"
                    :class="{ address_default: addressDefaultId == add.id }"
                  >
                    <view class="left">
                      <view class="address">
                        {{ add.detailAddress }}
                      </view>
                      <view class="member">
                        <text class="mr-10">
                          {{ add.name }}
                        </text>
                        <text>
                          {{ add.phone }}
                        </text>
                      </view>
                    </view>
                  </view>
                </view>
                <view class="" slot="body" v-else> 
                  <view class="u-body-item u-flex u-border-bottom">
                    您还没有收货地址,新增一个吧.
                  </view>
                </view>
              </u-card>
            </scroll-view>
          </view>

          <button type="primary" @tap="handlerAddNewAdd()">+新增地址</button>
        </view>
      </template>
    </popup-layer>
    <!-- 地址选择结束 -->

    <!-- <text-parse :showProps="textParseShow" :content="textParseContent">
    </text-parse> -->

    <popup-layer
      direction="top"
      :show-pop="textParseShow"
      class="remark_box"
      @openpopup="textParseShow = !textParseShow"
    >
      <template slot="content">
        <view class="text_box">
          <textarea
            name=""
            id=""
            cols="30"
            rows="10"
            :placeholder="textParsePopupPlaceholder"
            :value="textParsePopupContent"
            @input="inputTextParsePopupContent"
            maxlength="100"
          ></textarea>
        </view>

        <button type="primary" @tap.stop="handerCheckoutTextContent()">
          确定
        </button>
      </template>
    </popup-layer>

    <view
      class="pay_box w-100 position-fixed fixed-bottom d-flex align-items-center justify-content-between bg-white"
    >
      <view class="font-size-sm" style="margin-left: 20rpx">合计：</view>
      <!-- <view class="font-size-lg flex-fill">￥{{ amount }}</view> -->
      <view class="font-size-lg flex-fill">￥{{ cartTotalPrice }}</view>

      <view
        class="bg-primary h-100 d-flex align-items-center just-content-center text-color-white font-size-base"
        style="padding: 0 60rpx"
        @tap="submit()"
      >
        付款
      </view>
    </view>

    <u-toast ref="tips" :show="show"></u-toast>
  </div>
</template>

<script>
import popupLayer from "@/components/popup-layer/popup-layer";
import { mapState, mapMutations, mapActions, mapGetters } from "vuex";

export default {
  components: {
    popupLayer,
  },
  data() {
    return {
      show: false,
      content: "",
      orderType: "",
      takeOutTitle: "商家配送",
      orderOtherPrices: [
        {
          title: "包装费",
          price: 0,
        },
        {
          title: "配送费",
          price: 0,
        },
      ],
      zfbChecked: true,
      AddressPopupVisible: false, // popup 控制
      cart: [],

      selectListShow: false,
      selectList: [], // 时间选择器列表
      expectedReceiverTime: "", // 选择的时间
      order: {
        orderItemEntities: [
          // {
          // num: 0,  // 数量
          // productId: 0,  // ID
          // realAmount: 0, // 价格
          // saleAttrIdList: [0], // 销售属性
          // },
        ],
        realAmount: 0,
        receiverDetailAddress: "string",
        receiverName: "string",
        receiverPhone: "string",
        remark: "", // 备注
      },

      textParseShow: false,
      textParsePopupContent: "",
    };
  },
  onReady() {
    this.init();
  },
  async onShow() {
    // this.init();
    // 新建地址 - 返回页面后 刷新地址
    let _address = await this.$u.api.getUserAddressAll();
    this.$store.commit("SET_USER_ADDRESS", _address);
  },
  onHide() {
    console.log("page hide.");
  },
  computed: {
    ...mapState(["addressList", "addressDefaultId", "addressReceiver"]),
    ...mapGetters(["isLogin", "hasReceiverAddress"]),

    ...mapGetters(["getProduct"]),
    OrderItemImg() {
      return (id) => {
        try {
          if (this.getProduct(id).defaultImg)
            return this.getProduct(id).defaultImg;
        } catch (error) {
          return;
        }
      };
    },

    cardHeadClass() {
      return [
        { "background-image": "linear-gradient(45deg,blue,#fff)" },
        {
          display: "none",
        },
        {},
      ];
    },
    cardBodyClass() {
      return [
        {
          display: "none",
        },
      ];
    },
    takeOut() {},
    cartItem() {
      return {};
    },
    cartTotalPrice() {
      let _cartTotal = this.cart.reduce(
        (acc, cur) => acc + cur.number * cur.price ,
        0
      );
      let _otherTotal = this.orderOtherPrices.reduce(
        (acc, cur) => acc + cur.price,
        0
      );

      return _cartTotal + _otherTotal;
    },
    orderItemEntities() {},
    // 计算当前时间的三十分钟之后
    thirtyMinutesAfter() {
      let _date = new Date();
      _date.setMinutes(_date.getMinutes() + 30);
      let _hours = _date.getHours();
      let _minutes =
        _date.getMinutes() < 10 ? "0" + _date.getMinutes() : _date.getMinutes();
      return `${_hours}:${_minutes}`;
    },

    // text-parse-popup 的 placeholder
    textParsePopupPlaceholder() {
      if (!this.order.remark) {
        return "请在这里输入您的备注.";
      }
    },
  },

  methods: {
    ...mapMutations(["SET_DUFAULT_ADDRESS", "SET_RECEIVER_ADDRESS"]),
    init() {
      const that = this;
      let isEffectiveAddress = false;
      // 自取
      if (that.$store.state.orderType == "takein") {
        that.orderType = that.$store.state.orderType;
        that.takeOutTitle = "自取";
      } else {
        that.orderType = that.$store.state.orderType;
      }
      // 检查地址
      if (that.hasReceiverAddress) {
        console.log("has add.");
        // 检查是否是有效地址
        that.addressList.forEach((e) => {
          if (
            e.detailAddress == that.hasReceiverAddress.receiverDetailAddresss
          ) {
            isEffectiveAddress = true;
          }
        });
        if (!isEffectiveAddress) {
          that.hasReceiverAddress = {};
        }
      } else {
        console.log("no add.");
      }
      uni.getStorage({
        key: "cart-" + that.$store.state.member.userId,
        success(data) {
          // 可以生效
          that.cart = data.data;
        },
      });

      that.setSelectList();
    },

    // 选择时间的列表
    setSelectList() {
      let _date_start = new Date();
      let _date_end = new Date();
      _date_end.setHours(22);
      _date_end.setMinutes(0);
      _date_end.setSeconds(0);
      let _space = _date_end.getHours() - _date_start.getHours();

      let that = this;
      for (let i = 0; i < _space; i += 0.5) {
        _date_start.setMinutes(_date_start.getMinutes() + 30);
        let _h = _date_start.getHours();
        let _m =
          _date_start.getMinutes() < 10
            ? "0" + _date_start.getMinutes()
            : _date_start.getMinutes();
        that.selectList.push({
          value: `${_h}:${_m}`,
          label: `${_h}:${_m}`,
        });
      }
    },

    // 时间选择列表回调
    selectListConfirm(e) {
      console.log(e[0].value);
      console.log(this.expectedReceiverTime);
      this.expectedReceiverTime = e[0].value;
    },

    async handlerChooseReceiVerAddress() {
      // 然后渲染出来
      if (this.isLogin) {
        // 获取addresslist
        if (this.$store.state.addressList.length != 0) {
          this.showAddressSelect();
        } else {
          let _address = await this.$u.api.getUserAddressAll();
          this.$store.commit("SET_USER_ADDRESS", _address);
          this.showAddressSelect();
        }
      }
      // console.log(this.$store.state.addressList);
      // console.log(this.addressList.length);
      // this.showAddressSelect();
      // uni.navigateTo({
      //   url:'/pages/address/address'
      // })
    },
    showAddressSelect() {
      this.AddressPopupVisible = !this.AddressPopupVisible;
    },
    handlerChooseAddress(obj) {
      let add = obj;
      this.SET_DUFAULT_ADDRESS(add.id);
      this.showAddressSelect();
      this.SET_RECEIVER_ADDRESS(add.id);
      // this.AddressPopupVisible =
    },
    // 添加新地址
    handlerAddNewAdd() {
      // 跳转的问题
      uni.navigateTo({
        url: "/pages/address/newaddress",
      });
    },
    // 双向绑定
    inputTextParsePopupContent(e) {
      this.textParsePopupContent = e.target.value;
    },
    // 确认输入
    handerCheckoutTextContent() {
      console.log(this.textParsePopupContent);
      if (this.textParsePopupContent) {
        this.$set(this.order, "remark", this.textParsePopupContent);
        // this.textParsePopupContent  =
        this.textParseShow = !this.textParseShow;
      }
    },
    // 付款
    submit() {
      // 判断有无地址
      let that = this;
      let address = that.hasReceiverAddress;
      if (address) {
        // 可以执行
        // re
        that.order.orderItemEntities = [];
        console.log("可以执行付款");
        if (that.cart) {
          // push that.order.orderItemEntities
          that.cart.forEach((item) => {
            // console.log(item);
            that.order.orderItemEntities.push({
              // that.order.orderItemEntities 用来发送给api的参数
              num: item.number,
              productId: item.id,
              realAmount: item.price,
              saleAttrIdList: item.props,
            });

            // that.order.realAmount += item.price
          });
          console.log(that.order.orderItemEntities);
          // computed
          that.order.realAmount = that.cartTotalPrice;
          that.order.receiverDetailAddress =
            that.addressReceiver.receiverDetailAddresss;
          that.order.receiverName = that.addressReceiver.receiverName;
          that.order.receiverPhone = that.addressReceiver.receiverPhone;

          // send
          console.log(that.order.orderItemEntities);
          let params = JSON.parse(JSON.stringify(that.order));
          console.log(params);
          // return;
          that.$u.api.pushOrder(params).then((res) => {
            console.log(res);
            // 付款跳转.
            //  付款只要 orderSn
            // const sn = res.orderSn;
            //

            //

            uni.navigateTo({
              url: "../pay/alipay?sn=" + res.orderSn,
              // url: "@/pages/pay/alipay?sn=" + res.orderSn,
            });
          });
        }
      } else {
        that.$refs.tips.show({
          title: "请选择一个地址.",
          type: "warning",
        });
        that.AddressPopupVisible = !that.AddressPopupVisible;
      }
    },
  },
};
</script>

<style scoped lang="scss">
@import "./pay.scss";
</style>